package org.kongqian.car.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.kongqian.basic.utils.PageList;
import org.kongqian.car.es.doc.CarDoc;
import org.kongqian.car.es.repository.CarDocRepository;
import org.kongqian.car.query.CarSearchQuery;
import org.kongqian.car.service.ISearchListDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class SearchListDataServiceImpl implements ISearchListDataService {

    @Autowired
    private CarDocRepository repository;

    @Override
    public PageList searchListData(CarSearchQuery query) {
        //创建建造者
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        //高级查询
            //获取bool对象
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //查询
        String keyword = query.getKeyword();
        if (StringUtils.isNotBlank(keyword)){
            boolQuery.must(QueryBuilders.multiMatchQuery(keyword.trim(), "title","shopName","typeName","carInfo"));
        }

        //过滤
        List<QueryBuilder> filter = boolQuery.filter();
        Integer costeffective = query.getCosteffective();//是否超值
        Integer rushsale = query.getRushsale();//急售
        Integer quasinewcar = query.getQuasinewcar();// 准新车
        Integer transitivecountry = query.getTransitivecountry();//可迁全国
        Integer typeId = query.getTypeId();//车辆类型

        if (costeffective!=null){
            filter.add(QueryBuilders.termQuery("costeffective", costeffective)); //等值查询 a=1 的意思
        }
        if (rushsale!=null){
            filter.add(QueryBuilders.termQuery("rushsale", rushsale));
        }
        if (quasinewcar!=null){
            filter.add(QueryBuilders.termQuery("quasinewcar", quasinewcar));
        }
        if (transitivecountry!=null){
            filter.add(QueryBuilders.termQuery("transitivecountry", transitivecountry));
        }
        if (typeId!=null){
            filter.add(QueryBuilders.termQuery("typeId", typeId));
        }

        //车龄
        Integer carAge = query.getCarAge();
        Integer carAgeType = query.getCarAgeType();
        if (carAge !=null && carAgeType !=null){
            //当前时间-车龄 假如是2年 就是2020年的车 是carAgeType=0 就是以内 reigstertime>2020年 <new Date();
            //如果carAgeType=1 就是以上 reigstertime<=2020年
            carAge=0-carAge;
            Date date = DateUtils.addYears(new Date(), carAge);//这个方法是当前时间加上后面的参数，我们要的是减去后面的参数
            if (carAgeType==0){
                //进入这里说明是以内
                boolQuery.filter(QueryBuilders.rangeQuery("reigstertime").gte(date));
            }else if (carAgeType==1){
                //进入这里说明是以上
                boolQuery.filter(QueryBuilders.rangeQuery("reigstertime").lte(date));
            }
        }

        //排序
        String orderType = query.getOrderType();
        String orderField = query.getOrderField();
        SortOrder sortOrder = SortOrder.DESC;//默认倒序
        if ("asc".equals(orderType)){
            sortOrder= SortOrder.ASC;
        }

        if ("cost".equals(orderField)){
            //进入这里说明是给价格排序
            builder.withSort(SortBuilders.fieldSort("costprice").order(sortOrder));
        }else if ("latestRelease".equals(orderField)){
            //进去这里说明是给最新发布排序
            builder.withSort(SortBuilders.fieldSort("onsaletime").order(sortOrder));
        }else if ("age".equals(orderField)){
            //进去这里说明是给车龄排序
            builder.withSort(SortBuilders.fieldSort("reigstertime").order(sortOrder));
        }else if ("mileage".equals(orderField)){
            //进去这里说明是给里程排序
            builder.withSort(SortBuilders.fieldSort("mileage").order(sortOrder));
        }

        builder.withQuery(boolQuery);
        //分页
        builder.withPageable(PageRequest.of((query.getCurrentPage()-1 ), query.getPageNumber()));

        //分页数据 total pageData
        Page<CarDoc> search = repository.search(builder.build());
        List<CarDoc> data = search.getContent();
        for (CarDoc datum : data) {
            String shopAddress = datum.getShopAddress();
            shopAddress = shopAddress.split("市")[0];
            datum.setShopAddress(shopAddress);
        }
        Integer total =(int) search.getTotalElements();
        return new PageList<>(total,data);
    }
}
